package cn.tanghom.app.system.controller;

import cn.tanghom.app.system.model.Resources;
import cn.tanghom.app.system.model.User;
import cn.tanghom.app.system.service.ResourcesService;
import cn.tanghom.app.system.service.UserService;

import cn.tanghom.support.tree.TreeObject;
import cn.tanghom.support.tree.TreeUtil;
import cn.tanghom.support.web.BaseController;

import com.mysql.jdbc.Connection;

import org.flowable.engine.IdentityService;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.TaskService;
import org.flowable.task.api.Task;
import org.flowable.task.api.TaskQuery;
import org.apache.ibatis.jdbc.ScriptRunner;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import static cn.tanghom.support.web.BaseController.THEME_PATH;
/**
 * 首页控制器,
 *
 * @author tanghom
 */
@Controller
@RequestMapping
public class MainController {
    @Resource
    private UserService userService;
    
    @Resource
    private ResourcesService resourcesService;  
    
    @Autowired
	IdentityService identityservice;
    
    @Autowired
    RepositoryService repositoryService;
    
    @Autowired
    private TaskService taskService;
    
    /**
     * 主框架
     * @param model
     * @return
     */
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String root(Model model) {
        Subject currentUser = SecurityUtils.getSubject();
        String loginName = (String)currentUser.getPrincipal();
        User loger = userService.findByLoginName(loginName);
        Session session = currentUser.getSession();
        //session.setAttribute(CommonKey.USER_SESSION,loger);
        List<Resources> resources = new ArrayList<Resources>();
        if (1 == loger.getId() || loger.hasPermission("admin:menu")) {
            resources = resourcesService.findListByParams(1);
        } else {
            resources = resourcesService.findUserResourcess(loger.getId());
        }
        List<TreeObject> list = new ArrayList<TreeObject>();
        for (Resources res : resources) {
            TreeObject ts = new TreeObject();
            ts.setId(res.getId().intValue());
            ts.setName(res.getName());
            ts.setParentId(res.getParentId()==null?0:res.getParentId().intValue());
            ts.setResUrl(res.getUrl());
            ts.setResKey(res.getResKey());
            ts.setIcon(res.getIcon());
            list.add(ts);
        }
        TreeUtil treeUtil = new TreeUtil();
        List<TreeObject> menus = treeUtil.getChildTreeObjects(list, 0);
        model.addAttribute("menus", menus);
        return THEME_PATH + "/main";
    }
    
    
    /**
     * dashboard 
     * 主框架下的首页
     * @return
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(Model model) {    	
    	long userCount = identityservice.createUserQuery().count();
    	long groupCount = identityservice.createGroupQuery().count();
    	long modelCount = repositoryService.createModelQuery().count();
    	
    	Subject currentUser = SecurityUtils.getSubject();
    	TaskQuery taskQuery = taskService.createTaskQuery().taskCandidateOrAssigned(currentUser.getPrincipal().toString());
        long tasksCount = taskQuery.count();
    	
    	model.addAttribute("userCount",userCount);
    	model.addAttribute("groupCount",groupCount); 
    	model.addAttribute("modelCount",modelCount);
    	model.addAttribute("taskCount",tasksCount);
    	
        return THEME_PATH + "/index";
    }   
    
    /**
     * 安装基础数据库
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/install", method = RequestMethod.GET)
    @ResponseBody
    public String install() throws Exception {

        try {
            Properties props = org.apache.ibatis.io.Resources.getResourceAsProperties("jdbc.properties");
            String driver = props.getProperty("jdbc.driverClassName");
            String url = props.getProperty("jdbc.url");
            String username = props.getProperty("jdbc.username");
            String password = props.getProperty("jdbc.password");
            Class.forName(driver).newInstance();
            Connection conn = (Connection) DriverManager.getConnection(url, username, password);
            ScriptRunner runner = new ScriptRunner(conn);
            runner.setErrorLogWriter(null);
            runner.setLogWriter(null);
            InputStream in = getClass().getResourceAsStream("/sql/db_install.sql");
            if(in!=null){
            	runner.runScript((new InputStreamReader(in,"UTF-8")));
            }
            else{
            	return "读取sql/db_install.sql文件失败！";
            }

        } catch (Exception e) {
            e.printStackTrace();
            return "初始化失败！请联系管理员" + e;
        }

        return "初始化成功";
    }

}
